package cn.wolfcode.mq.listener;

import cn.wolfcode.MQ.MQConstant;
import cn.wolfcode.MQ.OrderMQResult;
import cn.wolfcode.common.web.Result;
import cn.wolfcode.mq.SeckillMessage;
import cn.wolfcode.service.IOrderInfoService;
import cn.wolfcode.web.msg.SeckillCodeMsg;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author zhangh
 * @version 1.0
 * @date 2025/9/23 18:40
 * @description 步骤二[创建订单] 监听 [异步下单]消息
 */
@Slf4j
@Component
@RocketMQMessageListener(
        consumerGroup = MQConstant.SECKILL_ORDER_GROUP,
        topic = MQConstant.SECKILL_ORDER_TOPIC)
public class SeckillOrderListener implements RocketMQListener<SeckillMessage> {

    @Autowired
    private IOrderInfoService orderInfoService;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Override
    public void onMessage(SeckillMessage message) {
        log.info("步骤二[创建订单]开始：{}", JSON.toJSONString(message));

        OrderMQResult result = new OrderMQResult();
        result.setToken(message.getToken());
        result.setSeckillId(Long.valueOf(message.getSeckillId()));
        try {

            // 异步执行下单操作 orderNo 订单号
            String orderNo = orderInfoService.doSeckillAsync(message.getSeckillId(), message.getUserId());

            // 订单创建成功
            result.setOrderNo(orderNo);
            result.setCode(Result.SUCCESS_CODE);
            result.setMsg("订单创建成功");

        }catch (Exception e){
            log.info(e.getMessage());
            // 订单创建失败
            result.setCode(Result.ERROR_CODE);
            result.setMsg("订单创建失败，e:"+e.getMessage());
        }

        // 创建websocket长连接，将创建订单结果返回给前端

        // [创建订单]推送消息到mq
        String destinationTopic = MQConstant.SECKILL_ORDER_RESULT_TOPIC;
        rocketMQTemplate.asyncSend(destinationTopic, result, new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                log.info("步骤二[创建订单]，异步消息发送成功! msgId: {}, topic: {}, status: {}",
                        sendResult.getMsgId(),
                        destinationTopic,
                        sendResult.getSendStatus());
            }

            @Override
            public void onException(Throwable throwable) {
                log.error("步骤二[创建订单]，异步消息发送失败! topic: {}, error: {}",
                        destinationTopic,
                        throwable.getMessage(),
                        throwable);
            }
        });


    }
}
